#include "ch.h"
#include "hal.h"
#include "hw_conf.h"

void gpio_init(void)
{
    //GPIO
    palSetPadMode(PCHG_SW_GPIO, PCHG_SW_PIN, PAL_MODE_OUTPUT_PUSHPULL |
                        PAL_STM32_OSPEED_HIGHEST);
    palClearPad(PCHG_SW_GPIO, PCHG_SW_PIN);
    
    palSetPadMode(PWR_BTN_GPIO, PWR_BTN_PIN, PAL_MODE_INPUT);
    
    palSetPadMode(PWR_SW_GPIO, PWR_SW_PIN, PAL_MODE_OUTPUT_PUSHPULL |
                        PAL_STM32_OSPEED_HIGHEST);
    palClearPad(PWR_SW_GPIO, PWR_SW_PIN);
    
    palSetPadMode(DSG_SW_GPIO, DSG_SW_PIN, PAL_MODE_OUTPUT_PUSHPULL |
                        PAL_STM32_OSPEED_HIGHEST);
    palClearPad(DSG_SW_GPIO, DSG_SW_PIN);
    palSetPadMode(CHG_SW_GPIO, CHG_SW_PIN, PAL_MODE_OUTPUT_PUSHPULL |
                        PAL_STM32_OSPEED_HIGHEST);
    palClearPad(CHG_SW_GPIO, CHG_SW_PIN);
    
    palSetPadMode(CHG_SENSE_GPIO, CHG_SENSE_PIN, PAL_MODE_INPUT_ANALOG);
    palSetPadMode(DSG_SENSE_GPIO, DSG_SENSE_PIN, PAL_MODE_INPUT_ANALOG);
    palSetPadMode(TEMP_SENSE_GPIO, TEMP_SENSE_PIN, PAL_MODE_INPUT_ANALOG);

#if defined(BATTMAN_4_2)
    palSetPadMode(USB_DETECT_GPIO, USB_DETECT_PIN, PAL_MODE_INPUT_PULLDOWN);
#endif
#if defined(BATTMAN_4_1) || defined(BATTMAN_4_2)
    palSetPadMode(CURR_ALERT_GPIO, CURR_ALERT_PIN, PAL_MODE_INPUT);
    palSetPadMode(RTCC_INT_GPIO, RTCC_INT_PIN, PAL_MODE_INPUT_PULLUP);
#endif

    // SPI
    palSetPadMode(LTC6803_CS_GPIO, LTC6803_CS_PIN, PAL_MODE_OUTPUT_PUSHPULL |
                        PAL_STM32_OSPEED_HIGHEST);

    palSetPad(LTC6803_CS_GPIO, LTC6803_CS_PIN);
    palSetPadMode(SCK_GPIO, SCK_PIN, PAL_MODE_ALTERNATE(5) | PAL_STM32_OSPEED_HIGHEST);
    palSetPadMode(MISO_GPIO, MISO_PIN, PAL_MODE_ALTERNATE(5) | PAL_STM32_OSPEED_HIGHEST | PAL_STM32_PUPDR_PULLUP);
    palSetPadMode(MOSI_GPIO, MOSI_PIN, PAL_MODE_ALTERNATE(5) | PAL_STM32_OSPEED_HIGHEST | PAL_STM32_OTYPE_PUSHPULL);

    // I2C
    palSetPadMode(SDA_GPIO, SDA_PIN, PAL_MODE_ALTERNATE(4) | PAL_STM32_OTYPE_OPENDRAIN | PAL_STM32_PUPDR_PULLUP | PAL_STM32_OSPEED_MID1);
    palSetPadMode(SCL_GPIO, SCL_PIN, PAL_MODE_ALTERNATE(4) | PAL_STM32_OTYPE_OPENDRAIN | PAL_STM32_PUPDR_PULLUP | PAL_STM32_OSPEED_MID1);

    // RGB LED
    palSetPadMode(LED_R_GPIO, LED_R_PIN, PAL_MODE_ALTERNATE(1));
    palSetPadMode(LED_G_GPIO, LED_G_PIN, PAL_MODE_ALTERNATE(1));
    palSetPadMode(LED_B_GPIO, LED_B_PIN, PAL_MODE_ALTERNATE(1));

    // Buzzer
    palSetPadMode(BUZZER_GPIO, BUZZER_PIN, PAL_MODE_ALTERNATE(1));

    // CAN
    palSetPadMode(CAN_RX_GPIO, CAN_RX_PIN, PAL_MODE_ALTERNATE(9) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_MID1 | PAL_STM32_PUPDR_PULLUP);
    palSetPadMode(CAN_TX_GPIO, CAN_TX_PIN, PAL_MODE_ALTERNATE(9) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_MID1);

    // USB
    palSetPadMode(USB_DM_GPIO, USB_DM_PIN, PAL_MODE_ALTERNATE(14));
    palSetPadMode(USB_DP_GPIO, USB_DP_PIN, PAL_MODE_ALTERNATE(14));
}
